/* eslint-disable no-param-reassign */
import { useStore } from '@/hooks';
import TauTable from '@/components/TauTable';
import { Button, Dialog, Form } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import DrawerFooter from '@/components/DrawerFooter';
import { TitleGrid, column } from '../stores/definitions_group';
import { observer } from 'mobx-react-lite';
import { observable } from 'mobx';


const FromItem = Form.Item;

const tableId = uniqueId('tauTable-');

const PartnerGroup = ({ modal, partnerRef, onCancel }) => {
  const { partnerGroupStore: store } = useStore();
  // 使用useRef进行拼接字段且不会造成重绘
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(modal[0] === 'check');
  const formProps = isViewMode ? { field: false } : {};
  const [partner] = useState(() => observable({}));
  const [parents, setParents] = useState([]);
  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    (async () => {
      const { id, partnerInfo } = partnerRef || {};
      const { inviteCode } = partnerInfo || {};
      store.search = {
        username: id,
      };
      try {
        await store.query();
        const res = await store.getInvite(inviteCode) || [];
        setParents([...res]);
      } catch (error) {
        console.log('🚀 _ file: PartnerGroup.jsx:40 _ error:', error);
      }
    })();
  }, []);

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(partner, name, value);
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };

  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      inline
      isPreview={isViewMode}
      {...formProps}
      value={partner}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`父级合伙人`} />
      <TauTable
        instanceId={tableId}
        primaryKey="id"
        tableLayout="fixed"
        hidePagination
        dataSource={parents}
        columns={[
          { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
          column('fullname', { width: 88 }),
          column('genderText', { width: 88 }),
          column('mobile', { width: 88 }),
          column('status', { width: 88 }),
        ]}
      />
      <TitleGrid title={t`子级合伙人`} />
      <TauTable
        instanceId={tableId}
        primaryKey="id"
        tableLayout="fixed"
        currentPage={store.pg.page}
        pageSize={store.pg.size}
        total={store.total}
        onFetch={(pg) => { store.pg = pg; }}
        loading={store.loading}
        dataSource={toJS(store.partner)}
        columns={[
          { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
          column('fullName', { width: 88 }),
          column('finished', { width: 88, cell: (v) => <span style={{ color: 'red' }}>{v / 100}</span> }),
          column('total', { width: 88, cell: (v) => <span style={{ color: 'green' }}>{v / 100}</span> }),
          column('memberId', { width: 88 }),
        ]}
      />
      <DrawerFooter>
        <FromItem>
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>
    </Form>
  );
};

export default observer(PartnerGroup);
